<?php
namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Models\video\CommonServer;
use App\Models\video\DataCacheModel;
use App\Models\video\VideoSettingModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WxMiniPublishController extends BaseController
{
    private $wxMiniRequestUrl = "https://update.netbcloud.com/public/index.php";
    private $checkUpdateRoute = "/wxApp/checkVersion"; // 检查更新
    private $invokeCodeRoute = "/wxApp/getInvokeCode"; //
    private $previewRoute = "/wxApp/previewByMini"; // window 发布机
    private $publishRoute = "/wxApp/publishByMini"; // window 发布机
    public function __construct(Request $request){
        parent::__construct($request);
    }

    // 检查更新
    public function index(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$request->projectName){
            $this->returnData = ErrorCode::$admin_enum["fail"];
            $this->returnData["msg"] = "项目名不存在";
            return $this->return_result($this->returnData);
        }
        if($request->projectName == '微购儿CRM') {
            $path = "pages/agent/homepage/index/index";
            $data = DB::table('wxapp_upgrade')->orderBy('create_time', 'desc')->where("mall_id", $request->mallData["id"])->select('version')->first();
        }else{
            $path = "pages/index/index";
            $data = DB::table('up_wxapp_upgrade')->orderBy('create_time','desc')->where("mall_id", $request->mallData["id"])->select('version')->first();
        }
        $version = !empty($data->version) ? $data->version : "0";
        $res = $this->curl($this->wxMiniRequestUrl.$this->checkUpdateRoute, json_encode(["version" => $version, "projectName" => $request->projectName]));
        $result = json_decode(trim($res, chr(239) . chr(187) . chr(191)), true);
        if(isset($result["code"])){
            if($result['code'] != 0){
                $results = ErrorCode::$admin_enum["fail"];
                $results["msg"] = $result["msg"];
                return $this->return_result($results);
            }else {
                if($result["status"] == '1') {
                    DataCacheModel::saveCache(["key" => "publish_".request()->token, "value" => [
                        "version" => $result["data"]['version'], "desc" => $result["data"]['remarks'], "projectName" => request()->projectName
                    ], "time" => 43200]);
                }
                $result['data']['path'] = $path;
                return $this->return_result($result);
            }
        }else{
            return $this->return_result(ErrorCode::$admin_enum['fail']);
        }
    }

    public function handleData($data){
        if($data['projectName'] == '微购儿CRM') {
            $settings = DB::table('configs')->where("mall_id", request()->mallData["id"])->select('member_wechat_appid','wx_mini_upload_key','wx_service_provider_ticket')->first();
            if(empty($settings->member_wechat_appid) || empty($settings->wx_mini_upload_key)){
                return ErrorCode::code('customized', '小程序未配置');
            }
            $setting["appId"] = $settings->member_wechat_appid;
            $setting["wxMiniUploadKey"] = $settings->wx_mini_upload_key;
            $setting["wxServiceProviderTicket"] = $settings->wx_service_provider_ticket;
        }else{
            $setting = VideoSettingModel::getFields("app_id,wx_mini_upload_key,wx_service_provider_ticket", ["mall_id" => request()->mallData["id"]], true, false);;
            if(empty($setting["appId"]) || empty($setting["wxMiniUploadKey"])){
                return ErrorCode::code('customized', '小程序未配置');
            }
        }
        $requestParams = [
            "projectName" => $data['projectName'], "version" => $data['version'],
            "appId" => $setting["appId"], "SaaS_ID" => request()->mallData["id"],
            "host" => CommonServer::getUrl('', false), "serviceProviderTicket" => $setting['wxServiceProviderTicket']
        ];
        $result = $this->curl($this->wxMiniRequestUrl.$this->invokeCodeRoute, json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != 0){
            return ErrorCode::code('customized', "error，{$res["msg"]}");
        }
        $data["token"] = $res["data"];
        $data["certKey"] = $setting["wxMiniUploadKey"];
        $data["appId"] = $setting["appId"];
        DataCacheModel::saveCache(["key" => "publish_".request()->token, "value" => $data, "time" => 43200]);
        return $data;
    }

    // 预览码
    public function previewByMini(Request $request){
        $cacheData = DataCacheModel::getValue("publish_".$request->token);
        if(empty($cacheData)){
            return $this->return_result(ErrorCode::code("customized", "错误"));
        }
        $cacheData = $this->handleData($cacheData);
        if(isset($cacheData["code"])){
            return $this->return_result($cacheData);
        }
        $cacheData["certKey"] = $cacheData["certKey"] ?: "";
        $requestParams = [
            "projectName" => $cacheData['projectName'], "appId" => $cacheData["appId"], "token" => $cacheData["token"], 'certKey' => $cacheData["certKey"],
            "desc" => $cacheData["desc"]
        ];
        $result = $this->curl($this->wxMiniRequestUrl.$this->previewRoute, json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != "0"){
            $this->returnData = ErrorCode::$admin_enum["fail"];
            $this->returnData["msg"] = isset($res["msg"]) ? $res["msg"] : "获取预览结果失败";
        }else {
            $this->returnData["data"] = $res["data"];
        }
        return $this->return_result($this->returnData);
    }

    // 发布
    public function publishByMini(Request $request){
        $cacheData = DataCacheModel::getValue("publish_".$request->token);
        if(empty($cacheData)){
            return $this->return_result(ErrorCode::code("customized", "错误"));
        }
        $cacheData["certKey"] = $cacheData["certKey"] ?: "";
        $requestParams = [
            "projectName" => $cacheData['projectName'], "appId" => $cacheData["appId"], "token" => $cacheData["token"], 'certKey' => $cacheData["certKey"],
            "desc" => $cacheData["desc"], 'version' => $cacheData['version']
        ];
        $result = $this->curl($this->wxMiniRequestUrl.$this->publishRoute, json_encode($requestParams));
        $res = json_decode(trim($result, chr(239) . chr(187) . chr(191)), true);
        if($res["code"] != "0"){
            $this->returnData = ErrorCode::$admin_enum["fail"];
            $this->returnData["msg"] = isset($res["msg"]) ? $res["msg"] : "获取上传结果失败";
        }else {
            if(!DB::table("wxapp_upgrade")->where("mall_id", $request->mallData["id"])->where("version", $cacheData['version'])->count()){
                DB::table('wxapp_upgrade')->insert(["version" => $cacheData['version'], "remarks" => $cacheData["desc"], "create_time" => time(), "mall_id" => $request->mallData["id"]]);
            }
            if($request->projectName == '微购儿CRM') {
                if(!DB::table("wxapp_upgrade")->where("mall_id", $request->mallData["id"])->where("version", $cacheData['version'])->count()){
                    DB::table('wxapp_upgrade')->insert(["version" => $cacheData['version'], "remarks" => $cacheData["desc"], "create_time" => time(), "mall_id" => $request->mallData["id"]]);
                }
            }else{
                if(!DB::table("up_wxapp_upgrade")->where("mall_id", $request->mallData["id"])->where("version", $cacheData['version'])->count()){
                    DB::table('up_wxapp_upgrade')->insert(["version" => $cacheData['version'], "remarks" => $cacheData["desc"], "create_time" => time(), "mall_id" => $request->mallData["id"]]);
                }
            }
            $this->returnData = $res;
        }
        return $this->return_result($this->returnData);
    }

    public function curl($url, $data = "", $header = ['Content-Type: application/json'], $timeout = 200)
    {
        $ch = curl_init($url);
        if(empty($data)){
            curl_setopt($ch, CURLOPT_HTTPGET, 1);
        }else {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        if(!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $output = curl_exec($ch);
        $errno = curl_errno($ch);
        if ($errno) {
            curl_close($ch);
            return false;
        }
        curl_close($ch);
        return $output;
    }
}